﻿#include "butterfly.h"
#include <QPainter>
#include <QMouseEvent>
#include <QRandomGenerator>
#include <QApplication>
#include <QScreen>
#include <QDebug>
Butterfly::Butterfly(QWidget *parent)
    : QWidget{parent}
{
    m_pixmap.load("./up.png");
    setFixedSize(m_pixmap.size());
    startTimer(100);
}

void Butterfly::fly(int min, int max)
{
    int steX = QRandomGenerator::global()->bounded(min,max);
    int steY = QRandomGenerator::global()->bounded(min,max);
    int curX = this->geometry().topLeft().x() + steX;
    int curY = this->geometry().topLeft().y() + steY;
    if(curX >= this->parentWidget()->size().rwidth())
    {
        curX  = 0;
    }
    if(curY >= this->parentWidget()->size().rheight())
    {
        curY  = 0;
    }
    this->move(curX,curY);
}

void Butterfly::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(rect(),m_pixmap);
}

void Butterfly::timerEvent(QTimerEvent *event)
{
    QString pathName = m_start ? "./up.png" : "./down.png";
    m_start = !m_start;
    m_pixmap.load(pathName);
    fly();
    update();
}

void Butterfly::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        //                          全局坐标    窗口坐标点
        //qDebug() << "globalPos:" << event->globalPos() << "," << "geometry:"<<this->geometry().topLeft();
        m_point = event->globalPos() - this->geometry().topLeft();
    }
}

void Butterfly::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton)
    {
        QPoint point = event->globalPos() - m_point;
        this->move(point);
    }
}

void Butterfly::enterEvent(QEvent *event)
{
    fly(-200,200);
}
